import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:quick_widget/drop_menu_container.dart';
import 'package:saas_order_meal/model/week_food_model.dart';
import 'package:saas_order_meal/net/net_response/customer_tag_data.dart';
import 'package:saas_order_meal/net/net_response/menu/food_tag_list_data.dart';
import 'package:saas_order_meal/ui/apply_meal_page.dart';

import '../model/order_request_data.dart';
import '../net/net_response/menu/regular_menu_data.dart';

typedef OnFoodSelectListener = Function(DaySelectFood dayFood);

class RegularMenuContainViewModel extends BaseViewModel {
  final OrderRequestData orderData;
  final bool isRegular;
  String? date;
  OnFoodSelectListener? selectListener;
  var menuModel = WeekFoodModel();
  ///长者健康标签
  List<CustomerTagData> oldTagList = [];
  RegularMenuContainViewModel(BuildContext? context, {required this.menuList,
  required this.orderData,this.isRegular = false,this.date,this.selectListener})
      : super(context);

  @override
  void onCreated() {
    getOldLimit();
    _initData();
    getOldTags();
  }

  Future<void> getOldLimit() async {
    try{
      var elderInfo =  await menuModel.getElderBindInfo(orderData.elderHumanId, date??"");
      var limitData = elderInfo.packageInfo;
      orderData.limitMap = {};
      if(limitData!=null){
        orderData.limitMap![1] = limitData.breakfastLimitMoney;
        orderData.limitMap![2] = limitData.lunchLimitMoney;
        orderData.limitMap![3] = limitData.dinnerLimitMoney;
      }
    }catch(e){
      orderData.limitMap = {};
      if(e is String){
        // showCupertinoDialog(context: context, builder: (context){
        //   return WillPopScope(child: CupertinoAlertDialog(
        //     content: Text(e,style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold,fontSize: 18),),
        //     actions: [
        //       TextButton(onPressed: (){
        //         finish();
        //         finish();
        //       }, child: CommonText('关闭',textColor: Colors.blue))
        //     ],
        //   ), onWillPop: (){
        //     return Future(() => false);
        //   });
        // },barrierDismissible: false);
      }else{
        print(e);
      }

    }
  }

  Future<void> getOldTags() async {
    try{
      oldTagList =  await menuModel.getCustomerTag(orderData.elderHumanId);
    }catch(e){
      print(e);
    }
  }

  void _initData(){
    for(var i =0;i<menuList.length;i++){
      var time = menuList[i];
       if(orderData.weekHasOrderedMeal!.isNotEmpty){
         // showToast(orderData.weekHasOrderedMeal!.length.toString());
         var hasMealList = orderData.weekHasOrderedMeal![date]??[];
         if(hasMealList.contains(time.timeSection)){
           time.hasOrderedRemark = "该餐段已点过餐了";
         }else{
           if(time.canSelectRemark.isNullOrEmpty()){
             if(selectTime==null){
               timeSelection = i;
               selectTime ??= time;
             }
           }
         }
       }else{
         if(orderData.hasOrderedMeal.contains(time.timeSection)){
           time.hasOrderedRemark = "该餐段已点过餐";
         }else{
           if(time.canSelectRemark.isNullOrEmpty()){
             if(selectTime==null){
               timeSelection = i;
               selectTime ??= time;
             }
           }
         }
       }

      for(var item in time.timeSectionList!){
        for(var food in (item.categaryList??<RegularMenuCategaryList>[])){
          food.disableRemark = time.hasOrderedRemark.isNullOrEmpty()?(time.canSelectRemark??""):time.hasOrderedRemark;
        }
      }
    }



    if(selectTime==null){

      // showToast(menuList.first.canSelectRemark??"");
      // // finish();
      selectTime = menuList.first;
      timeSelection = 0;

    }
    notifyListeners();
  }

  var controller = DropMenuController();
  List<RegularMenuData> menuList;

  var timeSelection = -1;
  RegularMenuData? selectTime;

  var selectedMealList = <SelectFoodData>[];
  var totalPrice = 0.0;

  void getSelectItem() {
    selectedMealList.clear();
    totalPrice = 0.0;
    for (var item in menuList) {
      debugPrint("menuMenuTypeId====>${item.menuTypeId}");
      var data = SelectFoodData(
          selectFood: [],
          timeSection: item.timeSection,
          timeSectionName: item.timeSectionName,
          price: 0,date: date??orderData.date,menuTypeId:item.menuTypeId);
      for (var type
          in (item.timeSectionList ?? <RegularMenuTimeSectionList>[])) {

        if (type.selectList.isNotEmpty) {
          if(!selectedMealList.contains(data)){
            data.selectFood.addAll(type.selectList);
            data.price+=type.selectPrice;
          }else{
            var index = selectedMealList.indexOf(data);
            selectedMealList[index].selectFood.addAll(type.selectList);
            selectedMealList[index].price+=type.selectPrice;
          }
          totalPrice += type.selectPrice;
        }
      }
      if(data.selectFood.isNotEmpty){
        selectedMealList.add(data);
      }
    }

    selectedMealList.sort((o1, o2) {
      return o1.timeSection!.compareTo(o2.timeSection!);
    });

    if(selectListener!=null){
      print("dayPrice11===>${totalPrice}");
      var dayFood = DaySelectFood(date: date??orderData.date??"", selectFood: selectedMealList, price: totalPrice);
      selectListener!(dayFood);
    }

  }

  Future<bool> checkTags(RegularMenuCategaryList food) async {

    if(food.goodsLabelList.isNotEmpty&&oldTagList.isNotEmpty&&food.number<=0){
      var fitList = <FoodTagListData>[];
      for(var foodTag in food.goodsLabelList){
        for(var oldTag in oldTagList){
          if(foodTag.labelId==oldTag.labelId){
            fitList.add(foodTag);
          }
        }
      }
      if(fitList.isNotEmpty){
        bool? result =  await showCupertinoDialog(context: context, builder: (context){
          return CupertinoAlertDialog(
            content: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: 10,),
                CommonText('该菜品与长者存在以下冲突：'),
                SizedBox(height: 10,),
                Wrap(
                  spacing: 10,
                  runSpacing: 10,
                  children: fitList.map((e) => CommonText(e.labelName,textColor: Colors.white).addToContainer(
                      color: Colors.red,
                      padding: EdgeInsets.symmetric(horizontal: 10,vertical: 4)
                  )).toList(),
                ),
                SizedBox(height: 10,),
                CommonText('确定要添加吗')
              ],
            ),
            actions: [
              TextButton(onPressed: (){
                Go().pop(result: false);
              }, child: Text('取消',style: TextStyle(color: Colors.grey,fontSize: 15),)),
              TextButton(onPressed: (){
                Go().pop(result: true);
              }, child: Text('确定',style: TextStyle(color: Colors.blue,fontSize: 15),)),
            ],
          );
        });
        return result??false;
      }else{
        return true;
      }
    }else{
      return true;
    }
  }

  void addClick(RegularMenuCategaryList food, RegularMenuTimeSectionList data) {
    if(!food.disableRemark.isNullOrEmpty()){
      showToast(food.disableRemark);
      return;
    }
    var max = data.selectNumber ?? 0;
    if ((food.status ?? 0) == 0) {
      if (max == 0 || data.selectList.length < max) {
        food.status = 1;
        food.number = 1;
        food.selected = true;
      } else {
        if(isRegular){
          food.status = 1;
          food.number ++;
          food.selected = true;

        }else{
          showToast("${data.categary}最多选择${data.selectNumber}个菜品");
          return;
        }
      }
    } else {
      food.number++;
    }
    getSelectItem();
    notifyListeners();
  }

  void removeClick(RegularMenuCategaryList food) {
    food.number--;
    if (food.number == 0) {
      food.status = 0;
      food.selected = false;
    }
    getSelectItem();

    notifyListeners();
  }

  void multiChooseClick(
      RegularMenuCategaryList food, RegularMenuTimeSectionList data) {
    var max = data.selectNumber ?? 0;
    if (max == 0) {
      if ((food.status ?? 0) == 0) {
        food.status = 1;
        food.number = 1;
        food.selected = true;
      } else {
        food.status = 0;
        food.number = 0;
        food.selected = false;
      }
    } else if (max == 1) {
      if (food.status == 1) {
        food.status = 0;
        food.number = 0;
        food.selected = false;
      } else {
        for (var item in (data.categaryList ?? <RegularMenuCategaryList>[])) {
          item.status = 0;
          item.number = 0;
          food.selected = false;
        }
        food.status = 1;
        food.number = 1;
        food.selected = true;
      }
    } else {
      if (food.status == 0 && data.selectList.length >= max) {
        showToast("${data.categary}最多选择${data.selectNumber}个菜品");
      } else {
        if ((food.status ?? 0) == 0) {
          food.status = 1;
          food.number = 1;
          food.selected = true;
        } else {
          food.status = 0;
          food.number = 0;
          food.selected = false;
        }
      }
    }
  }

  Widget bottomContent() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          children: [
            CommonText('已选商品').setWeight(1),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Icon(
                  Icons.delete_outline,
                  color: Colors.grey[800],
                  size: 18,
                ),
                CommonText('清空', textSize: 14, textColor: Colors.grey[800]!)
              ],
            ).onTap(() {
              clearSelected();
              notifyListeners();
              controller.hide();
            })
          ],
        ).addToContainer(
            margin: EdgeInsets.symmetric(horizontal: 16, vertical: 16)),
        ListView.separated(
          padding: EdgeInsets.symmetric(horizontal: 16),
          shrinkWrap: true,
          itemBuilder: (context, index) {
            var item = selectedMealList[index];
            return selectMealItem(item);
          },
          separatorBuilder: (context, index) {
            return Divider();
          },
          itemCount: selectedMealList.length,
        ).setWeight(1)
      ],
    ).addToContainer(color: Colors.white,constraints: BoxConstraints(
      maxHeight: MediaQuery.of(context).size.height*0.6
    ));
  }

  void clearSelected() {
    if (selectedMealList.isEmpty) {
      return;
    }
    for (var item in selectedMealList) {
      for (var food in item.selectFood) {
        food.status = 0;
        food.number = 0;
      }
    }
    selectedMealList.clear();
    getSelectItem();
    notifyListeners();
  }

  Widget selectMealItem(SelectFoodData item) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 8,
        ),
        Row(
          children: [
            CommonText(
                "${item.timeSectionName}",
                textSize: 17,
                textColor: Colors.grey[700]!,
                fontWeight: FontWeight.bold)
                .setWeight(1),
            CommonText("¥${item.price}",
                textSize: 17, textColor: Colors.red),
          ],
        ),
        Container(
          height: 15,
        ),
        CommonText(
            item.selectFood.map((e) => "${e.goodsName}x${e.number}").join("、"),
            textColor: Colors.grey[800]!,
            textSize: 17),
        Container(
          height: 15,
        ),
      ],
    );
  }


  Future<void> toApplySubmit() async {
    if(selectedMealList.isEmpty){
      return;
    }
    orderData.selectFood = selectedMealList;
    orderData.totalPrice = totalPrice;
    var data = await Go().push(ApplyMealPage(orderData: orderData));
    if(data!=null){
      Go().pop(result: "true");
    }
  }
}

class SelectFoodData {
  num? timeSection;
  String? timeSectionName;
  List<RegularMenuCategaryList> selectFood = [];
  num price;
  bool hasSubmit = false;
  bool hasPaid = false;
  dynamic orderId;
  String? date;
  dynamic menuTypeId;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is SelectFoodData &&
          runtimeType == other.runtimeType &&
          timeSection == other.timeSection &&
          timeSectionName == other.timeSectionName;

  @override
  int get hashCode => timeSection.hashCode ^ timeSectionName.hashCode;

  SelectFoodData(
      {this.timeSection,
      this.timeSectionName,
      required this.selectFood,
      required this.price,
      this.hasSubmit = false,
      this.hasPaid = false,
      this.orderId,required this.date,this.menuTypeId});

  Map<String, dynamic> toMap() {
    return {
      'timeSection': this.timeSection,
      'timeSectionName': this.timeSectionName,
      'price': this.price,
      'date': this.date,
      'menuTypeId': this.menuTypeId,
      'selectFood': this.selectFood.map((e) => e.toJson()).toList(),
    };
  }

  factory SelectFoodData.fromMap(Map<String, dynamic> map) {
    return SelectFoodData(
      timeSection: map['timeSection'] as num,
      price: map['price'] as num,
      date: map['date'],
      menuTypeId: map['menuTypeId'],
      timeSectionName: map['timeSectionName'] as String,
      selectFood: map['selectFood'] as List<RegularMenuCategaryList>,
    );
  }

  SelectFoodData copyWith({
    num? timeSection,
    String? timeSectionName,
    List<RegularMenuCategaryList>? selectFood,
    num? price,
    bool? hasSubmit,
    bool? hasPaid,
    dynamic? orderId,
    dynamic? menuTypeId,
  }) {
    return SelectFoodData(
      timeSection: timeSection ?? this.timeSection,
      timeSectionName: timeSectionName ?? this.timeSectionName,
      selectFood: selectFood ?? this.selectFood,
      price: price ?? this.price,
      hasSubmit: hasSubmit ?? this.hasSubmit,
      hasPaid: hasPaid ?? this.hasPaid,
      orderId: orderId ?? this.orderId,
      date: date ?? this.date,
      menuTypeId: menuTypeId ?? this.menuTypeId,
    );
  }
}

class DaySelectFood{
  String date;
  List<SelectFoodData> selectFood;
  num price;

  DaySelectFood({required this.date,required this.selectFood,required this.price});
}
